package com.cmy.framework_utils.preference

import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import android.preference.PreferenceManager
import android.text.TextUtils

 abstract class BasePreferences {

        protected var sApplication: Application? = null

    protected var mPreference: SharedPreferences? = null

    open fun BasePreferences() {
        mPreference = if (TextUtils.isEmpty(getSPFileName())) {
            PreferenceManager.getDefaultSharedPreferences(sApplication)
        } else {
            sApplication!!.getSharedPreferences(getSPFileName(), Context.MODE_PRIVATE)
        }
    }

    protected abstract fun getSPFileName(): String?

    open fun getString(key: String?, defValue: String?): String? {
        return mPreference!!.getString(key, defValue)
    }

    open fun getBoolean(key: String?, defBool: Boolean): Boolean? {
        return mPreference!!.getBoolean(key, defBool)
    }

    open fun setBoolean(key: String?, bool: Boolean) {
        val editor = mPreference!!.edit()
        editor.putBoolean(key, bool)
        editor.commit()
    }

    open fun setLong(key: String?, value: Long) {
        val editor = mPreference!!.edit()
        editor.putLong(key, value)
        editor.commit()
    }

    open fun getLong(key: String?, defValue: Long): Long {
        return mPreference!!.getLong(key, defValue)
    }

    open fun getString(key: String?): String? {
        return mPreference!!.getString(key, "")
    }

    open fun setString(key: String?, value: String?) {
        val editor = mPreference!!.edit()
        editor.putString(key, value)
        editor.commit()
    }

    open fun getInt(key: String?, defaultVal: Int): Int {
        return mPreference!!.getInt(key, defaultVal)
    }

    open fun setInt(key: String?, value: Int) {
        val editor = mPreference!!.edit()
        editor.putInt(key, value)
        editor.commit()
    }

    open fun remove(key: String?) {
        if (!TextUtils.isEmpty(key) && mPreference!!.contains(key)) {
            val editor = mPreference!!.edit()
            editor.remove(key)
            editor.commit()
        }
    }

    open operator fun contains(key: String?): Boolean {
        return mPreference!!.contains(key)
    }

    open fun clearAll() {
        val editor = mPreference!!.edit()
        editor.clear()
        editor.commit()
    }

    open fun getAll(): Map<String?, *>? {
        return mPreference!!.all
    }
}